package com.tsd.core.datasource;

import cn.hutool.db.Entity;
import com.alibaba.druid.pool.DruidDataSource;
import com.tsd.core.utils.HlpUtils;

import java.util.Map;

/**
 * @Author Luoyc
 * @Date 2018/12/11 16:34
 * @Version
 * @Description: 数据源持有类
 */
public class DataSourceContextHolder {

    /**
     * 默认账套sid
     */
    public static final String DEFAULT_ACCOUNT_SET_SID = "tsd";

    private static final ThreadLocal<String> DATA_SOURCE_KEY = new InheritableThreadLocal<>();

    /**
     * 设置数据源类型
     * 需要在controller里面进行数据源设置或者新建线程
     * @param dataSourceType 数据库类型
     */
    public static void setDataSourceType(String dataSourceType) {
        if (HlpUtils.isEmpty(dataSourceType) || DEFAULT_ACCOUNT_SET_SID.equals(dataSourceType)) {
            DATA_SOURCE_KEY.remove();
        } else {
            DATA_SOURCE_KEY.set(dataSourceType.trim());
        }
    }

    /**
     * 获取数据源类型
     *
     * @return String 数据源类型
     */
    public static String getDataSourceType() {
        String datasource = DATA_SOURCE_KEY.get();
        if (HlpUtils.isEmpty(datasource)) {
            return DEFAULT_ACCOUNT_SET_SID;
        } else {
            return datasource;
        }
    }

    /**
     * 清除数据源类型
     */
    public static void clearDataSourceType() {
        DATA_SOURCE_KEY.remove();
    }

    /**
     * 判断当前账套是否主数据源
     *
     * @return Boolean
     */
    public static boolean isMaster() {
        return DEFAULT_ACCOUNT_SET_SID.equals(getDataSourceType());
    }

    public static DruidDataSource getMasterDataSource() {
        return SpringContextUtil.getBean("masterDataSource", DruidDataSource.class);
    }

    public static DruidDataSource getDataSource() {
        return getDataSource(getDataSourceType());
    }

    public static DruidDataSource getDataSource(Object key) {
        return (DruidDataSource) DynamicDataSource.getTargetDataSource().get(key);
    }

    public static Entity getAccountSet() {
        return getAccountSet(getDataSourceType());
    }

    public static Entity getAccountSet(Object key) {
        Map<Object, Entity> entityMap = DataSourceInitService.getAccountSetMap();
        if (entityMap == null || entityMap.isEmpty()) {
            return null;
        }
        return entityMap.get(key);
    }
}
